﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Facebook;
using System.Security;
using System.Runtime.InteropServices;  
using CommonLibrary;


namespace GUI
{	
	public partial class MainWindow : Form
	{
		[DllImport("wininet.dll", SetLastError = true)]
		private static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int lpdwBufferLength);  

		#region  Events
		/// <summary>
		/// Event that is fired when the program is closing.
		/// </summary>
		public event ProgramClosingDelegate programClosingEvt;
		#endregion Events

		#region Public properties

		#endregion Public properties

		#region Private properties
		private const int INTERNET_OPTION_END_BROWSER_SESSION = 42;

		private const string FB_WWW  = "http://www.facebook.com";
		private const string FB_LOGOUT_WWW = "http://www.facebook.com/logout.php?api_key={0}&session_key={1}&next={2}";
		
		/// <summary>
		/// Gets or sets application Id.
		/// </summary>
		private SecureString AppId { get; set; }
		/// <summary>
		/// Gets or sets application Secret key.
		/// </summary>
		private SecureString AppSecret { get; set; }

		private string AccessToken { get; set; }

		public FacebookOAuthResult FacebookOAuthResult { get; private set; }
		#endregion Private properties

		#region Constructors
		/// <summary>
		/// Non-parametric constructor used for designer.
		/// </summary>
		public MainWindow()
		{
			InitializeComponent();
		}
		/// <summary>
		/// Constructor.
		/// </summary>
		/// <param name="appId">Application id key.</param>
		/// <param name="appSecret">Application secret key</param>
		public MainWindow(SecureString appId, SecureString appSecret)
		{
			InitializeComponent();

			this.AppId = appId;
			this.AppSecret = appSecret;

			this.webBrowser1.Navigate(this.GetLoginUrl());
		}
		#endregion Constructors

		#region Private methods
		/// <summary>
		/// Displays page with facebook login dialog.
		/// </summary>
		/// <returns></returns>
		private Uri GetLoginUrl()
		{
			var oauth = new FacebookOAuthClient
			{
				AppId = this.AppId.SecureStringToString(),
				AppSecret = this.AppSecret.SecureStringToString()
			};

			var parameters = new Dictionary<string, object>
                    {
                        { "response_type", "token" },
                        { "display", "popup" }
                    };
			string[] extendedPermissions = new[] { "publish_stream", "offline_access" };
			var scope = new StringBuilder();
			scope.Append(string.Join(",", extendedPermissions));
			parameters["scope"] = scope.ToString();
			

			var loginUrl = oauth.GetLoginUrl(parameters);
			return loginUrl;
		}

		/// <summary>
		/// NOT WORKING.
		/// </summary>
		/// <returns></returns>
		private Uri GetLogoutUrl()
		{	
			char[] tokenSeparator = new char[] { '|' };
			string session = this.AccessToken.Split(tokenSeparator)[1];
			string logoutUrl = string.Format(FB_LOGOUT_WWW, this.AppId,session,FB_WWW);
			return new Uri(logoutUrl);
		}

		private void wbBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
		{			
			FacebookOAuthResult result = null;
			if (FacebookOAuthResult.TryParse(e.Url, out result))
			{
				if (result.IsSuccess)
				{
					this.FacebookOAuthResult = result;
					this.AccessToken = result.AccessToken;
					this.btnLogout.Enabled = true;
				}
				else
				{
					string errorDescription = result.ErrorDescription;
					string errorReason = result.ErrorReason;
					this.FacebookOAuthResult = null;
				}
			}
		}
		/// <summary>
		/// Fires event that the form was closed.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void MainWindow_FormClosed(object sender, FormClosedEventArgs e)
		{
			if (this.programClosingEvt != null)
			{
				programClosingEvt(this, null);
			}
		}

		private void btnLogout_Click(object sender, EventArgs e)
		{
			this.webBrowser1.Navigate(this.GetLogoutUrl());
		}

		private void MainWindow_Load(object sender, EventArgs e)
		{
			InternetSetOption(IntPtr.Zero, INTERNET_OPTION_END_BROWSER_SESSION, IntPtr.Zero, 0);
			this.webBrowser1.Navigate(this.GetLoginUrl());
		}


		#endregion Private methods



	
	}
}
